//
//  PGoodHeadCell.m
//  yigou
//
//  Created by wangdianlei on 2017/1/19.
//  Copyright © 2017年 hanyiwang. All rights reserved.
//

#import "PGoodHeadCell.h"

@implementation PGoodHeadCell  {
    UICollectionView *mcollectionView;
}

- (void)awakeFromNib {
    [super awakeFromNib];
    // Initialization code
    self.title =  [[UITextField alloc] initWithFrame:CGRectMake(12, 0, ScreenWidth - 24, 50)];
    _title.placeholder =@"输入标题(名称)";
    _title.textAlignment = NSTextAlignmentLeft;
    _title.font = [UIFont systemFontOfSize:15];
    _title.delegate = self;
    [self.contentView addSubview:self.title];
    
    UIView *line1 = [[UIView alloc] initWithFrame:CGRectMake(0, 49, ScreenWidth, 1)];
    line1.backgroundColor = LineColor;
    [self.contentView addSubview:line1];
    
    UICollectionViewFlowLayout *flowlayout = [[UICollectionViewFlowLayout alloc]init];
    //    flowlayout.minimumInteritemSpacing = 5;
    //    flowlayout.minimumLineSpacing = 5;
    //    flowlayout.itemSize = CGSizeMake((kScreenWidth-24-15)/4, 52);
    self.itemWidth = (ScreenWidth - 24 - 24 * 3) / 4;
    flowlayout.itemSize = CGSizeMake(self.itemWidth, self.itemWidth);
    // 设置最小行间距
    flowlayout.minimumLineSpacing = 19;
    // 设置垂直间距
    flowlayout.minimumInteritemSpacing = 24;
    
    mcollectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(12, 50 + 24, ScreenWidth-24, self.itemWidth + 19) collectionViewLayout:flowlayout];
    [self.contentView addSubview:mcollectionView];
    mcollectionView.backgroundColor = [UIColor whiteColor];
    
    [mcollectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.contentView.mas_left).offset(12);
        make.right.equalTo(self.contentView.mas_right).offset(-12);
        make.height.mas_equalTo(self.itemWidth + 19);
        make.top.equalTo(self.title.mas_bottom).offset(24);
    }];
    [mcollectionView registerClass:[PublishTopicImageCell class] forCellWithReuseIdentifier:@"PublishTopicImageCell"];
    mcollectionView.delegate = self;
    mcollectionView.dataSource = self;
    [mcollectionView reloadData];
}

- (void)textFieldDidEndEditing:(UITextField *)textField {
    [PublishData sharedPublishData].product_title = self.title.text;
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];

    // Configure the view for the selected state
}

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return ([PublishData sharedPublishData].goodimgArray.count + 1);
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    
    PublishTopicImageCell *cell = (PublishTopicImageCell *)[collectionView dequeueReusableCellWithReuseIdentifier:@"PublishTopicImageCell" forIndexPath:indexPath];
    cell.indexPath = indexPath;
    cell.delegate = self;
    if ([PublishData sharedPublishData].goodimgArray.count > 0) {
        if (indexPath.row == [PublishData sharedPublishData].goodimgArray.count) {
            cell.deletebtn.hidden = YES;
            cell.icon.image = [UIImage imageNamed:@"post_Camera"];
        } else {
            cell.deletebtn.hidden = NO;
            UIImage *img = [PublishData sharedPublishData].goodimgArray[indexPath.row];
            cell.icon.image = img;
        }
    } else {
        cell.deletebtn.hidden = YES;
        cell.icon.image = [UIImage imageNamed:@"post_Camera"];
    }
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    [self.contentView endEditing:YES];
    if ([PublishData sharedPublishData].goodimgArray.count == 0) {
        [self clickAdd];
    } else {
        if (indexPath.row == [PublishData sharedPublishData].goodimgArray.count) {
            [self clickAdd];
        }
    }
}

- (void)publishTopicDeleteOne:(NSIndexPath *)indexPath {
    NSInteger index = indexPath.row;
    [[PublishData sharedPublishData].goodimgArray removeObjectAtIndex:index];
    NSInteger count = ([PublishData sharedPublishData].goodimgArray.count + 1) / 4 + (([PublishData sharedPublishData].goodimgArray.count + 1) % 4 > 0 ? 1 : 0);
    [mcollectionView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo((self.itemWidth + 19) * count);
    }];
    [mcollectionView reloadData];
    
    if (self.controller) {
        PublishGoodViewController *pb = (PublishGoodViewController *)self.controller;
        [pb refreshTable];
    }
}

- (void)clickAdd {
    [self.contentView endEditing:YES];
    UIAlertController* alertVC = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    
    UIAlertAction* cancleAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    
    UIAlertAction* takePhotoAction = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self openCamera];
    }];
    
    UIAlertAction* choosePictureAction = [UIAlertAction actionWithTitle:@"从手机相册选择" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self choosePhoto];
    }];
    
    [alertVC addAction:cancleAction];
    [alertVC addAction:takePhotoAction];
    [alertVC addAction:choosePictureAction];
    
    if (self.controller)
        [self.controller presentViewController:alertVC animated:YES completion:nil];
}

- (void)openCamera {
    UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
    
    if (![UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera]) {
        sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    }
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    picker.delegate = self;
    picker.sourceType = sourceType;
    
    if (self.controller)
        [self.controller presentViewController:picker animated:YES completion:^{
    }];
}

- (void)choosePhoto {
    NSInteger maxCount = 10;
    if (ISIOS7 || ISIOS8_0) {
        ELCImagePickerController *elcPicker = [ELCImagePickerController new];
        elcPicker.maximumImagesCount = maxCount;
        elcPicker.imagePickerDelegate = self;
        
        if (self.controller)
            [self.controller presentViewController:elcPicker animated:YES completion:nil];
    } else {
        QBImagePickerController *imagePickerController = [QBImagePickerController new];
        imagePickerController.assetCollectionSubtypes =@[
                                                         @(PHAssetCollectionSubtypeSmartAlbumUserLibrary), //相机胶卷
                                                         @(PHAssetCollectionSubtypeAlbumMyPhotoStream), //我的照片流
                                                         @(PHAssetCollectionSubtypeSmartAlbumPanoramas), //全景图
                                                         @(PHAssetCollectionSubtypeSmartAlbumBursts), //连拍模式拍摄的照片
                                                         @(PHAssetCollectionSubtypeSmartAlbumFavorites)
                                                         ];
        imagePickerController.delegate = self;
        imagePickerController.allowsMultipleSelection = YES;
        imagePickerController.mediaType = QBImagePickerMediaTypeImage;
        imagePickerController.maximumNumberOfSelection = maxCount;
        imagePickerController.showsNumberOfSelectedAssets = YES;
        
        if (self.controller)
            [self.controller presentViewController:imagePickerController animated:YES completion:nil];
    }
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(NSDictionary *)editingInfo {
    [picker dismissViewControllerAnimated:YES completion:^{
        [[PublishData sharedPublishData].goodimgArray insertObject:image atIndex:0];
        NSInteger count = ([PublishData sharedPublishData].goodimgArray.count + 1) / 4 + (([PublishData sharedPublishData].goodimgArray.count + 1) % 4 > 0 ? 1 : 0);
        [mcollectionView mas_updateConstraints:^(MASConstraintMaker *make) {
            make.height.mas_equalTo((self.itemWidth + 19) * count);
        }];
        [mcollectionView reloadData];
        
        if (self.controller) {
            PublishGoodViewController *pb = (PublishGoodViewController *)self.controller;
            [pb refreshTable];
        }
    }];
}

- (void)elcImagePickerController:(ELCImagePickerController *)picker didFinishPickingMediaWithInfo:(NSArray *)info
{
    //TODO:changeToData
    [picker dismissViewControllerAnimated:YES completion:^{
        for (int i = 0;i<[info count];i++) {
            UIImage *img = [[info objectAtIndex:i]objectForKey:@"UIImagePickerControllerOriginalImage"];
            [[PublishData sharedPublishData].goodimgArray insertObject:img atIndex:0];
        }
        NSInteger count = ([PublishData sharedPublishData].goodimgArray.count + 1) / 4 + (([PublishData sharedPublishData].goodimgArray.count + 1) % 4 > 0 ? 1 : 0);
        [mcollectionView mas_updateConstraints:^(MASConstraintMaker *make) {
            make.height.mas_equalTo((self.itemWidth + 19) * count);
        }];
        [mcollectionView reloadData];
        
        if (self.controller) {
            PublishGoodViewController *pb = (PublishGoodViewController *)self.controller;
            [pb refreshTable];
        }
    }];
}

- (void)elcImagePickerControllerDidCancel:(ELCImagePickerController *)picker {
    [picker dismissViewControllerAnimated:YES completion:^{
        DYLog(@"cancl");
    }];
}

- (void)qb_imagePickerController:(QBImagePickerController *)imagePickerController didFinishPickingAssets:(NSArray *)assets {
    NSUInteger count = assets.count;
    __block NSUInteger select = 0;
    PHImageRequestOptions *option = [[PHImageRequestOptions alloc] init];
    option.synchronous = YES;
    for (PHAsset *asset in assets) {
        [[PHCachingImageManager defaultManager]requestImageDataForAsset:asset options:option resultHandler:^(NSData * imageData, NSString * dataUTI, UIImageOrientation orientation, NSDictionary * info) {
            if(imageData) {
                [[PublishData sharedPublishData].goodimgArray insertObject:[UIImage imageWithData:imageData] atIndex:0];
                select++;
            }
            if(select == count) {
                NSInteger count = ([PublishData sharedPublishData].goodimgArray.count + 1) / 4 + (([PublishData sharedPublishData].goodimgArray.count + 1) % 4 > 0 ? 1 : 0);
                [mcollectionView mas_updateConstraints:^(MASConstraintMaker *make) {
                    make.height.mas_equalTo((self.itemWidth + 19) * count);
                }];
                [mcollectionView reloadData];
                
                if (self.controller) {
                    PublishGoodViewController *pb = (PublishGoodViewController *)self.controller;
                    [pb refreshTable];
                }
                
                [imagePickerController dismissViewControllerAnimated:YES completion:NULL];
                
                return;
            }
        }];
        
    }
}

- (void)qb_imagePickerControllerDidCancel:(QBImagePickerController *)imagePickerController {
    [imagePickerController dismissViewControllerAnimated:NO completion:NULL];
}

@end
